
########################################################################
###                  Binary Response Models                          ###
########################################################################
rm(list = ls()) # clean the global environment
# dev.off() # erase all the previous plots
# press ctrl+L to erase text in console

# a) ########################################################################
library(wooldridge)
library(sandwich)
library(lmtest)
data("loanapp")
help(loanapp)

# Linear Probability Model
ols = lm(approve ~white+price+hrat,data=loanapp)
# heteroscedasticity robust standard errors
coeftest(ols, vcov = vcovHC(ols))
# ceteris paribus the predicted probability of being approved for a mortgage loan increases by
# 19.4% (0.194) for white applicants compared to non-white applicants.

# b) ########################################################################
phat = ols$fitted.values
summary(phat)
#estimated predicted probabilities not being constrained between 0 and 1

# c) ########################################################################
# logit model
logit<-glm(approve ~white+price+hrat,data=loanapp,family=binomial(link="logit"))
summary(logit)

# d) ########################################################################
# average price and hrat
x1 = mean(loanapp$price)
x2 = mean(loanapp$hrat)

# white applicant
z1 = logit$coefficients%*%c(1,1,x1,x2)
p.w = exp(z1)/(1+exp(z1))
# non-white applicant
z0 = logit$coefficients%*%c(1,0,x1,x2)
p.nw = exp(z0)/(1+exp(z0))

# difference in probabilities:
p.w-p.nw

# e) ########################################################################
library(mfx)
# Calculating marginal effects at the average: logit
logitmfx(approve ~white+price+hrat,data=loanapp,atmean = TRUE)
# Calculating marginal effects at the average: probit
probitResult=probitmfx(approve ~white+price+hrat,data=loanapp,atmean = TRUE)
print(probitResult)
#compare to ols
summary(ols)
